<template>
  <div class="audit-progress-wrap">
    <el-timeline v-if="flowStructure && flowStructure.process.length > 0" class="not-icon-timeline">
      <el-timeline-item
        v-for="(struct, index) in flowStructure.process"
        :key="index"
        :class="classList[struct.nodeStatus]"
        :color="struct.nodeStatus === 0 || struct.nodeStatus === 1? '#406EFF': '#DDE1EA'"
        size="large"
      >
        <div class="process-item-block">
          <div v-for="(role, roleIndex) in struct.examineRoles" :key="role.id" class="process-item-row">
            <div v-if="selectData.process[index]" :style="{'min-height': processItemMinHeight + 'px'}" class="process-item-box">
              <div class="process-dec-wrap">
                <div class="process-dec">
                  <span v-if="struct.nodeType === 3 && roleIndex === 0" class="process-name">{{ struct.nodeName }}</span>
                  <span v-else class="process-name">{{ role.roleName }}<span v-if="struct.nodeType !== 4 && role.status === 3 && showPress" class="press-btn" @click="pressSend(role, struct)">催办</span></span>
                </div>
              </div>
              <div :style="{marginTop: !selectData.process[index].examineRoles[roleIndex].aduitors.length && '6px', marginBottom: roleIndex === struct.examineRoles.length - 1 && '0'}" class="auditor-select-box">
                <AuditorAvatar :is-fly-user="role.roleType === ROLE_TYPE.FLYNOTICE" :slice-num="showMobilePage ? 1 : 2" :user-list="selectData.process[index].examineRoles[roleIndex].aduitors" sort-user />
                <div :class="`status status${role.status}`">
                  {{ role.status | mapOptions(statusOptions) }}
                </div>
                <div v-if="!disable && struct.isCountersign === 1 && operateData.auth.includes(6) && selectData.process[index].examineRoles[roleIndex].aduitors.length === 0" class="select-item">
                  <add-btn :size="avatorSize" :relation="struct.roleRelation" :show-relation="roleIndex < struct.examineRoles.length -1" @add="addAudit(role, index, roleIndex)"/>
                </div>
                <el-button
                  v-if="selectData.process[index].examineRoles[roleIndex].aduitors.length >= 2"
                  type="text"
                  style="color: #406EFF; font-size: 14px; font-weight: bold"
                  class="select-item"
                  @click="checkMore(index, roleIndex, selectData.process[index].examineRoles[roleIndex].roleName, struct, role.roleType === ROLE_TYPE.FLYNOTICE)">
                  查看全部</el-button>
              </div>
            </div>
          </div>
          <!-- 审批倒计时提示 -->
          <div v-if="struct.nodeStatus === 1 && struct.timeLeft" style="height: 20px" />
          <div v-if="struct.nodeStatus === 1" :class="struct.timeLeft && 'process-countdown-box'">
            <template v-if="!struct.countdownEnd">
              <Countdown v-if="struct.timeLeft" :count="struct.timeLeft">
                <template slot-scope="remainingTime">
                  <template v-if="remainingTime.restCount != null">
                    <div v-if="remainingTime.restCount > 0">
                      距离审批超时：
                      <template v-if="formatCountdownUnit(remainingTime, 'day')">{{ remainingTime.day }}天</template>
                      <template v-if="formatCountdownUnit(remainingTime, 'hour')">{{ remainingTime.hour }}小时</template>
                      <template v-if="formatCountdownUnit(remainingTime, 'minute')">{{ remainingTime.minute }}分</template>
                      <template>{{ remainingTime.second }}秒</template>
                    </div>
                    <div v-else>审批已超时</div>
                  </template>
                  <div v-else>审批时间加载中...</div>
                </template>
              </Countdown>
            </template>
            <div v-else>审批已超时</div>
          </div>
        </div>
      </el-timeline-item>
    </el-timeline>
    <div v-if="senders.length" class="process-item-block sender-container">
      <div class="sender-box-header">
        <span style="font-weight: bold">抄送</span>
        <span class="sender-box-header-tip">(共抄送{{ senders.length }}人)</span>
      </div>
      <div class="sender-box-content">
        <AuditorAvatar :user-list="senders" :slice-num="showMobilePage ? 1 : 2"/>
        <el-button v-if="senders.length > 1" type="text" class="check-more" @click="handleShowAllSender">查看全部</el-button>
      </div>
    </div>
    <auditor-dialog ref="auditorShowAllDialog" />
    <divers-auditor-dialog ref="auditorDialog" :is-comfirm="true" comfirm-text="加签人确认后无法修改" @userSelect="userSelect" />
    <ding-ding-dialog
      ref="pressSendDialogRef"
      :all-dept-list="allDeptList"
      :btn1="'确认加急'"
      :btn2="'取消'"
      :auth-url="authUrl"
      :show-send-checkbox="false"
      :select-with-user-load="false"
      :default-list="defaultList"
      :redirect-url="redirectUrl"
      summary-title="加急原因"
      title="催办通知"
      @handelOK="toSend" />
    <auditor-check-all-dialog ref="auditorCheckAllDialogRef" :users="users" :title="checkAllTitle" :dialog-form-visible="dialogFormVisible" @close="auditorCheckAllClose" />
  </div>
</template>
<script>
import AddBtn from './module/addBtn';
import CheckMoreBtn from './module/checkMoreBtn';
import AuditorCheckAllDialog from './module/auditorCheckAllDialog';
import AuditorAvatar from './module/auditorAvatar';
import { mapOptions } from '@/filters';
import AuditorDialog from './module/auditorDialog';
import DiversAuditorDialog from './module/diversAuditorDialog';
import DingDingDialog from '@/components/Customer/detail/dialog';
import Countdown from '@/components/Common/countdown';
import { ROLE_TYPE } from '@/utils/const/process';
import { mapState } from 'vuex';
export default {
  name: 'AuditProgressWrap',
  components: {
    AddBtn,
    CheckMoreBtn,
    AuditorDialog,
    DiversAuditorDialog,
    DingDingDialog,
    Countdown,
    AuditorAvatar,
    AuditorCheckAllDialog },
  filters: {
    mapOptions
  },
  props: {
    flowStructure: {
      type: Object,
      default: () => {
        return null;
      }
    },
    processData: {
      type: Object,
      default: () => {
        return null;
      }
    },
    operateData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    avatorSize: {
      type: Number,
      default: 40
    },
    processItemMinHeight: {
      type: Number,
      default: 65
    },
    disable: { // 是否可编辑 false: 可编辑
      type: Boolean,
      default: false
    },
    // 是管理员或创建者
    hasPressAuth: { // 是否可编辑 false: 可编辑
      type: Boolean,
      default: false
    },
    // 审批流状态
    processStatus: {
      type: Number,
      default: 0
    },
    defaultAduitorList: { // 申请人
      type: Array,
      default: () => {
        return [];
      }
    },
    defaultAuthUserList: { // 授权人
      type: Array,
      default: () => {
        return [];
      }
    },
    senders: { // 抄送人
      type: Array,
      default: () => []
    },
    // 钉钉跳转地址
    redirectUrl: {
      type: String,
      default: '/legal/contractDetail'
    }
  },
  data() {
    return {
      ROLE_TYPE,
      //  0：结束 1：进行中 2：未审批
      classList: [
        'node-end',
        'node-ing',
        'node-unexecuted'
      ],
      statusOptions: [
        { value: 0, label: '已作废' },
        { value: 1, label: '已提交' },
        { value: 2, label: '已撤回' },
        { value: 3, label: '审批中' },
        { value: 4, label: '已审批' },
        { value: 5, label: '未过审' },
        { value: 6, label: '未审批' },
        { value: 7, label: '已转交' },
        { value: 8, label: '待提交' },
        { value: 11, label: '未抄送' },
        { value: 12, label: '已抄送' },
        { value: 13, label: '部分审批' },
        { value: 14, label: '退回节点' }
      ],
      allDeptList: [],
      // 钉钉通知人员列表，筛选有审批权限的人
      authUrl: 'crm:customer:examine',
      // 是否打开页面首次请求
      requestFirst: true,
      // 所有审核人
      allExamineUserList: [],
      defaultList: [],
      // 进程id
      processId: '',
      users: [],
      dialogFormVisible: false,
      checkAllTitle: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    }),
    selectData: {
      get() {
        return this.processData;
      },
      set(val) {
        this.$emit('change', val);
      }
    },
    // 是否展示催办按钮
    // 审批流状态为审核中并且(是创建者或者管理员或者审批人员)
    showPress() {
      return this.processStatus === 1 &&
      (this.hasPressAuth || this.allExamineUserList.find(i => i.id === this.userInfo.id));
    }
  },
  created() {
    const allExamineUserList = [];
    this.flowStructure.process.map((process, index) => {
      if ((process.nodeName === '任务发起' && index === 0) || process.nodeType === 3) {
        return;
      }
      process.examineRoles.map((item) => {
        item.aduitors.forEach((aduitors) => {
          if (!allExamineUserList.find(i => i.id === aduitors.id)) {
            allExamineUserList.push(aduitors);
          }
        });
      });
    });
    this.allExamineUserList = allExamineUserList;
  },
  methods: {
    addAudit(examineRole, index, roleIndex, title = '添加加签人') {
      const aduitors = this.selectData.process[index].examineRoles[roleIndex].aduitors;
      const param = {
        index,
        roleIndex,
        aduitors,
        isAddSigner: true,
        examineRoleId: examineRole.id,
        roleType: examineRole.roleType,
        departmentList: examineRole.departmentList,
        defaultAduitorList: examineRole.roleType === ROLE_TYPE.PROPOSER ? this.defaultAduitorList : this.defaultAuthUserList,
        allowSelectOther: examineRole.allowSelectOther
      };
      this.$refs.auditorDialog.dialogVisible = true;
      this.$refs.auditorDialog.initData(param, title);
    },
    checkMore(index, roleIndex, title = '审批人', struct = {}, isFlyNotice = false) {
      const aduitors = this.selectData.process[index].examineRoles[roleIndex].aduitors;
      this.users = aduitors || [];
      this.dialogFormVisible = true;
      if (this.$refs.auditorCheckAllDialogRef) this.$refs.auditorCheckAllDialogRef.initData(isFlyNotice);
      this.checkAllTitle = struct.nodeType === 3 ? struct.nodeName : title;
    },
    auditorCheckAllClose() {
      this.dialogFormVisible = false;
      this.users = [];
      this.checkAllTitle = '';
    },
    addSender(param, title = '添加抄送人') {
    },
    userSelect(param) {
      const index = param.tempData.index;
      const roleIndex = param.tempData.roleIndex;
      const examineRolesId = this.selectData.process[index].examineRoles[roleIndex].id;
      const data = {
        id: examineRolesId,
        aduitors: param.selectUser
      };
      this.$emit('addSigner', data);
    },
    // 返回数组的前两个
    returnArr(arr) {
      const length = arr.length > 2 ? 1 : arr.length;
      const temp = [];
      for (let i = 0; i < length; i++) {
        temp.push(arr[i]);
      }
      return temp;
    },
    // 展示催办弹窗
    pressSend(examineRole, struct) {
      const defaultUser = [];
      this.processId = struct.id;
      // 默认通知人员为该节点上的所有人员
      examineRole.aduitors.forEach((aduitors) => {
        if (!defaultUser.find(i => i.id === aduitors.id)) {
          defaultUser.push(aduitors);
        }
      });
      this.defaultList = defaultUser;
      const msg = '';
      this.$refs.pressSendDialogRef.showDialog({
        defaultMsg: msg,
        defaultUser
      });
    },
    toSend(data) {
      // 添加钉钉通知配置
      this.$emit('pressSendMsg', Object.assign(data, { id: this.processId }));
    },
    // 展示所有抄送人
    handleShowAllSender() {
      this.users = this.senders;
      this.dialogFormVisible = true;
      this.checkAllTitle = '所有人员';
    },
    formatCountdownUnit(time, curUnit) {
      const units = ['day', 'hour', 'minute'];
      if (!time || !units.includes(curUnit)) return;
      let showUnit = false;
      switch (curUnit) {
        case units[0]:
          showUnit = (time[units[0]] === '0');
          break;
        case units[1]:
          showUnit = (time[units[0]] === '0' && time[units[1]] === '0');
          break;
        case units[2]:
          showUnit = (time[units[0]] === '0' && time[units[1]] === '0' && time[units[2]] === '0');
          break;
      }
      return !showUnit;
    }
  }
};
</script>
<style lang="scss" scoped>
$status:
  // #F9EBEB #E02020 1 0, // 草稿
  #406EFF #fff 1 1, // 提交
  #E02020 #fff 5 2, // 撤回
  #FD8546 #fff 3 3, // 审批中
  #31CC9C #fff 4 4, // 已审批
  #E02020 #fff 5 5, // 未过审
  #999999 #fff 6 6, // 未审批
  #999999 #fff 7 7, // 已转交
  #FD8546 #fff 3 8, // 待提交
  #999999 #fff 6 11, // 未抄送
  #406EFF #fff 4 12, // 已抄送
  #FD8546 #fff 3 13; // 部分审批
%background {
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
}
.status {
  min-width: 48px;
  padding: 0 6px;
  height: 20px;
  font-size: 12px;
  //margin-top: 12px;
  background: #FFEFE6;
  border-radius: 999px;
  line-height: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  .icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-left: 4px;
    @extend %background;
  }
}
@each $bgc, $color, $bg, $i in $status {
  .status#{$i} {
    background: $bgc;
    color: $color;
     @if $i != 7 {
      .icon {
        background-image: url('~@/assets/auditProcess/status#{$bg}.png');
      }
    }
  }
}
.audit-progress-wrap {
  width: 100%;
  margin-top: 14px;
  .node-end,
  .node-begin,
  .node-ing,
  .node-unexecuted {
    &::v-deep {
      .el-timeline-item__node {
        width: 16px;
        height: 16px;
        background-color: transparent!important;
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100%;
        margin-top: 12px;
      }
    }
  }
  .node-end {
    &::v-deep {
      .el-timeline-item__node {
        background-image: url('~@/assets/auditProcess/status4.png');
      }
    }
  }
  .node-begin {
    &::v-deep {
      .el-timeline-item__node {
        background-image: url('~@/assets/auditProcess/status1.png');
      }
    }
  }
  .node-ing {
    &::v-deep {
      .el-timeline-item__node {
        background-image: url('~@/assets/auditProcess/status3.png');
      }
    }
  }
  .node-unexecuted {
    &::v-deep {
      .el-timeline-item__node {
        background-image: url('~@/assets/auditProcess/status6.png');
      }
    }
  }
  & ::v-deep {
    .el-timeline {
      padding-left: 0;
    }
    .el-timeline-item__tail {
      margin-top: 12px;
      left: 4px;
    }
    .el-timeline-item:last-child {
      .el-timeline-item__tail {
        display: none!important;
      }
    }
    .el-timeline-item {
      padding-bottom: 12px;
    }
    .el-timeline-item__timestamp.is-bottom {
      margin-top: 0;
    }
    .el-timeline-item__wrapper {
      top: -4px;
      padding-left: 18px;
    }
  }
  .process-item-block {
    padding: 12px 16px 12px 12px;
    background: #fff;
    box-shadow: 0 3px 6px #DDE1EA;
    opacity: 1;
    border-radius: 8px;
  }
  .sender-container {
    margin: 0 0 16px 18px;
    .sender-box-header {
      font-size: 16px;
      color: #333;
      display: flex;
      align-items: center;
      &-tip {
        color: #999;
        font-size: 14px;
        margin-left: 6px;
      }
    }
    .sender-box-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 12px;
      .check-more {
        color: #406eff;
        font-size: 14px;
        cursor: pointer;
        font-weight: bold;
      }
    }
  }
  .process-item-box {
    //display: flex;
    // padding-bottom: 9px;
    .process-dec-wrap {
      display: flex;
      flex: 1;
      .require-flag {
        margin-right: 10px;
        color: #E54C4C;
      }
      .process-dec {
        display: flex;
        flex: 1;
        flex-direction: column;
        width: 0;
        .process-name {
          display: block;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          font-size: 16px;
          color: #333333;
          font-weight: bold;
        }
        .auditor-num {
          margin-top: 2px;
          font-size: 14px;
          color: #999999;
        }
      }
    }
  }
  .process-countdown-box {
    position: absolute;
    width: calc(100% - 18px);
    transform: translate(-12px, -12px);
    padding-left: 12px;
    background: #FFEFF0;
    height: 24px;
    color: #FF4E5F;
    line-height: 24px;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 3px 6px #DDE1EA;
  }
  .auditor-select-box,
  .sender-select-box {
    display: flex;
    align-items: center;
    margin-top: 12px;
    margin-bottom: 24px;
    .select-item {
      position: absolute;
      right: 12px;
    }
    //.select-item:first-child {
    //  &::before {
    //    content: " ";
    //    display: block;
    //    margin: 0;
    //  }
    //}
    //.select-item::before {
    //  content: "+";
    //  display: flex;
    //  align-items: center;
    //  margin: 0 10px;
    //  font-size: 20px;
    //  color: #999;
    //}
  }
  .send-to {
    display: flex;
    margin-top: 17px;
    margin-left: 26px;
    .send-to-dec {
      display: flex;
      flex-direction: column;
      margin-right: 17px;
      .title {
        margin-bottom: 6px;
        font-size: 18px;
        color: #333333;
      }
      .send-num {
        font-size: 14px;
        color: #999999;
      }
    }
  }
}
.none-process {
  text-align: center;
  position: relative;
  margin-top: 20px;
  img {
    width: 90px;
  }
  .empty-text {
    color: #999;
    font-size: 14px;
  }
}
.press-btn {
  padding-left: 10px;
  color: #406EFF;
  cursor: pointer;
}
</style>
